package com.dong.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dong.system.entity.Menu;
import com.dong.system.mapper.MenuMapper;
import com.dong.system.service.MenuService;
import com.dong.system.vo.MenuVO;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author dongjian
 * @since 2021-01-23
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    // 1. map<id, menuVO>
    // List<Menu>  遍历 - parentId(菜单id)

    // MenuVO -> addList

    // 2. groupBy(pid) ->   map<pid,list>
    // List<Menu>  遍历 - parentId(菜单id)


    @Override
    public List<MenuVO> getMenuVOS(String userId) {
        List<MenuVO> menuVOS = Lists.newArrayList();
        List<Menu> list = this.lambdaQuery().orderByAsc(Menu::getOrderNum).list();
        list.stream().forEach(l -> {
            MenuVO menuVO = new MenuVO();
            BeanUtils.copyProperties(l, menuVO);
            menuVOS.add(menuVO);
        });
        Map<Long, List<MenuVO>> menuVOMap = menuVOS.stream().collect(Collectors.groupingBy(MenuVO::getParentId));
        return menuVOS.stream()
                .peek(m -> m.setChildren(menuVOMap.get(m.getId())))
                .filter(MenuVO::isRootNode)
                .collect(Collectors.toList());
    }

}
